'use strict';

const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');
const { v4: uuidv4 } = require('uuid');

class CommonService extends Service {

  /**
   * @description: 刷新token
   * @return {*}
   */
  async refreshToken() {
    const { ctx } = this;
    try {
      const newToken = ctx.helper.generateToken(ctx.helper.getUserIdByHeader(ctx), 60 * 1000 * 24);
      ctx.service.cache.set(ctx.helper.getUserIdByHeader(ctx), newToken, 60 * 60);
      return ctx.helper.body.SUCCESS({ ctx, msg: '', data: newToken });
    } catch (e) {
      ctx.logger.error('重新生成token失败', e);
      return ctx.helper.body.ERROR({ ctx, msg: '重新生成token失败' });
    }
  }

  /**
   * @description: 获取数字验证码
   * @return {*}
   */
  getCaptchaCode() {
    const { ctx } = this;
    const uuid = uuidv4();
    const options = {// 参数
      size: 4, // 验证码长度
      fontSize: 45, // 验证码字号
      noise: 2, // 干扰线条数目
      width: 120, // 宽度
      height: 40, // 高度
      color: true, // 验证码字符是否有颜色，默认是没有，但是如果设置了背景颜色，那么默认就是有字符颜色
    };
    const Captcha = svgCaptcha.createMathExpr(options); // 生成验证码
    ctx.service.cache.set(`code_${uuid}`, { captchaCode: Captcha.text, captchaUuid: uuid }, 60 * 5); // redis存储验证码
    ctx.logger.info('===获取验证码值===', Captcha.text);
    ctx.logger.info('===生成uuid===', uuid);
    return ctx.helper.body.SUCCESS({ ctx, msg: '验证码获取成功', data: { img: Captcha.data, uuid } });
  }

  /**
   * @description: 发送邮箱验证码
   * @param {*} payload
   * @return {*}
   */
  async sendMailer(payload) {
    const { ctx, app } = this;
    const { email } = payload;
    const code = ctx.helper.randomNum(6);
    await ctx.service.cache.set(`code_${email}`, code, 60 * 5); // redis存储验证码
    await app.mailer.send({
      from: '"去见APP" <2726653264@qq.com>', // sender address, [options] default to user
      // // Array => ['bar@example.com', 'baz@example.com']
      to: [ email ], // list of receivers
      subject: '去见APP', // Subject line
      text: code, // string
      html: `<div style="display: flex;flex-direction: column;justify-content: center;align-items: center;
                    width: 300px;height: 300px;box-shadow: 0px 0px 10px #ccc;border-radius: 30px;margin: 66px auto;">
                  <img width="100" src="https://avatars.githubusercontent.com/u/35050738?v=4" alt="">
                  <span style="line-height: 36px;">来自 去见APP - 遇见不一样的人生 邮箱验证码(有效时长5分钟)：</span>
                  <div style="font-weight: 600;font-size: 22px;line-height: 46px;">${code}</div>
                </div>`, // html body
    });
    return ctx.helper.body.SUCCESS({ ctx, msg: `验证码已发送至${email}邮箱`, data: null });
  }

  /**
   * @description: 验证邮箱验证码
   * @param {*} payload
   * @return {*}
   */
  async emailVerify(payload) {
    const { ctx } = this;
    const { email, code, is_reg } = payload;
    if (is_reg) {
      const user = await ctx.model.TAppUsers.findOne({ attributes: [ 'id' ], where: { email: payload.email } });
      if (user) {
        return ctx.helper.body.ERROR({ ctx, msg: '邮箱已被注册使用' });
      }
    }
    const cacheCode = await ctx.service.cache.get(`code_${email}`);
    if (!cacheCode) {
      return ctx.helper.body.ERROR({ ctx, msg: '验证码不正确或已过期' });
    } else if (code === cacheCode) {
      await ctx.service.cache.set(`code_${email}`, code, 1);
      return ctx.helper.body.SUCCESS({ ctx, msg: '验证成功' });
    }
    return ctx.helper.body.ERROR({ ctx, msg: '验证码不正确' });
  }
}

module.exports = CommonService;
